using System;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using WpfMedia = System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Interop;
using System.Windows.Media;
using TxTReader.Services;

namespace TxTReader.UI
{
    /// <summary>
    /// GoToLineWindow.xaml 的交互逻辑
    /// </summary>
    public partial class GoToLineWindow : Window
    {
        private readonly SettingsService _settingsService;
        private int _totalLines;
        
        /// <summary>
        /// 跳转请求事件（当用户点击确定时触发）
        /// </summary>
        public event Action<int>? GoToRequested;
        
        /// <summary>
        /// 获取用户输入的行号（如果成功，返回实际行号；如果失败，返回0）
        /// </summary>
        public int LineNumber { get; private set; }
        
        public GoToLineWindow(SettingsService settingsService, int totalLines)
        {
            InitializeComponent();
            
            // 设置窗口图标（跳转/箭头图标）
            SetWindowIcon();
            
            _settingsService = settingsService;
            _totalLines = totalLines;
            
            // 订阅主题变化事件
            ThemeService.ThemeChanged += OnThemeChanged;
            
            // 在窗口加载完成后应用主题和设置
            Loaded += (s, e) =>
            {
                ApplyTheme(ThemeService.GetCurrentTheme());
                LoadSettings();
            };
            
            // 窗口加载后聚焦到输入框
            Loaded += (s, e) => LineNumberTextBox.Focus();
        }
        
        /// <summary>
        /// 窗口关闭时取消主题订阅
        /// </summary>
        protected override void OnClosed(EventArgs e)
        {
            ThemeService.ThemeChanged -= OnThemeChanged;
            base.OnClosed(e);
        }
        
        /// <summary>
        /// 加载设置
        /// </summary>
        private void LoadSettings()
        {
            var settings = _settingsService.Settings;
            CloseAfterGoToCheckBox.IsChecked = settings.CloseAfterGoTo;
        }
        
        /// <summary>
        /// 保存设置
        /// </summary>
        private async void SaveSettings()
        {
            var settings = _settingsService.Settings;
            settings.CloseAfterGoTo = CloseAfterGoToCheckBox.IsChecked ?? false;
            await _settingsService.UpdateSettingsAsync(settings);
        }
        
        /// <summary>
        /// 选项变化时立即保存
        /// </summary>
        private void OnCloseAfterGoToChanged(object sender, RoutedEventArgs e)
        {
            SaveSettings();
        }
        
        /// <summary>
        /// 主题变化事件处理
        /// </summary>
        private void OnThemeChanged(ThemeInfo theme)
        {
            Dispatcher.Invoke(() => ApplyTheme(theme));
        }
        
        /// <summary>
        /// 计算与背景色对比鲜明的文本颜色
        /// </summary>
        private WpfMedia.Brush GetContrastColor(WpfMedia.Brush backgroundBrush)
        {
            if (backgroundBrush is WpfMedia.SolidColorBrush solidBrush)
            {
                var color = solidBrush.Color;
                // 计算相对亮度 (Rec. 709 标准)
                double luminance = 0.2126 * color.R / 255.0 + 0.7152 * color.G / 255.0 + 0.0722 * color.B / 255.0;
                
                // 如果背景较暗，使用亮色文本；如果背景较亮，使用暗色文本
                if (luminance < 0.5)
                {
                    // 背景较暗，使用亮色文本
                    return new WpfMedia.SolidColorBrush(WpfMedia.Color.FromRgb(255, 255, 255));
                }
                else
                {
                    // 背景较亮，使用暗色文本
                    return new WpfMedia.SolidColorBrush(WpfMedia.Color.FromRgb(0, 0, 0));
                }
            }
            // 如果不是SolidColorBrush，返回默认颜色
            return WpfMedia.Brushes.Black;
        }
        
        /// <summary>
        /// 应用主题
        /// </summary>
        private void ApplyTheme(ThemeInfo theme)
        {
            // 应用窗口背景
            Background = theme.WindowBackground;
            
            // 根据背景计算对比鲜明的文本颜色
            var contrastForeground = GetContrastColor(theme.WindowBackground);
            
            // 显式处理控件
            if (PromptText != null)
            {
                PromptText.Foreground = contrastForeground;
            }
            
            if (LineNumberTextBox != null)
            {
                LineNumberTextBox.Foreground = contrastForeground;
                LineNumberTextBox.Background = theme.TextBackground;
                LineNumberTextBox.BorderBrush = contrastForeground;
            }
            
            if (CloseAfterGoToCheckBox != null)
            {
                CloseAfterGoToCheckBox.Foreground = contrastForeground;
            }
            
            if (GoToButton != null)
            {
                GoToButton.Foreground = contrastForeground;
                GoToButton.BorderBrush = theme.MenuBackground;
                GoToButton.Background = theme.MenuBackground;
            }
            
            if (CancelButton != null)
            {
                CancelButton.Foreground = contrastForeground;
                CancelButton.BorderBrush = theme.MenuBackground;
                CancelButton.Background = theme.MenuBackground;
            }
        }
        
        /// <summary>
        /// 文本输入验证（只允许数字）
        /// </summary>
        private void OnPreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            // 只允许数字输入
            Regex regex = new Regex("[^0-9]+");
            e.Handled = regex.IsMatch(e.Text);
        }
        
        /// <summary>
        /// 处理回车键
        /// </summary>
        private void OnTextBoxKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                OnGoToClick(sender, e);
            }
            else if (e.Key == Key.Escape)
            {
                OnCancelClick(sender, e);
            }
        }
        
        /// <summary>
        /// 跳转按钮点击事件
        /// </summary>
        private void OnGoToClick(object sender, RoutedEventArgs e)
        {
            // 获取输入的行号
            if (string.IsNullOrWhiteSpace(LineNumberTextBox.Text))
            {
                MessageBox.Show("请输入行号", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                LineNumberTextBox.Focus();
                return;
            }
            
            // 解析行号（取整处理小数）
            if (!int.TryParse(LineNumberTextBox.Text, out int inputLineNumber))
            {
                // 如果是小数，先转换
                if (double.TryParse(LineNumberTextBox.Text, out double doubleValue))
                {
                    inputLineNumber = (int)Math.Floor(doubleValue);
                }
                else
                {
                    MessageBox.Show("请输入有效的数字", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    LineNumberTextBox.Focus();
                    return;
                }
            }
            
            // 容错处理
            if (inputLineNumber < 1)
            {
                // 负数或0，跳转到第1行
                LineNumber = 1;
            }
            else if (inputLineNumber > _totalLines)
            {
                // 超过总行数，跳转到最后一行
                LineNumber = _totalLines;
            }
            else
            {
                LineNumber = inputLineNumber;
            }
            
            // 触发跳转事件，通知主窗口执行跳转
            GoToRequested?.Invoke(LineNumber);
            
            // 如果设置了跳转后关闭窗口，则关闭窗口
            if (CloseAfterGoToCheckBox.IsChecked ?? false)
            {
                Close();
            }
            else
            {
                // 窗口保持打开，清空输入框以便下次输入
                LineNumberTextBox.Text = string.Empty;
                LineNumberTextBox.Focus();
            }
        }
        
        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        private void OnCancelClick(object sender, RoutedEventArgs e)
        {
            // 窗口是通过Show()打开的，不是ShowDialog()，所以不需要设置DialogResult
            Close();
        }
        
        /// <summary>
        /// 设置窗口图标（跳转/箭头图标）
        /// </summary>
        private void SetWindowIcon(System.Drawing.Icon? icon = null)
        {
            try
            {
                // 创建跳转图标（向右箭头）
                // 使用Path绘制：线条箭头
                var arrowPath = "M8,6 L20,12 L8,18 L8,14 L2,14 L2,10 L8,10 Z";
                var geometry = Geometry.Parse(arrowPath);
                var drawing = new GeometryDrawing(
                    new SolidColorBrush(System.Windows.Media.Color.FromRgb(255, 152, 0)), // 橙色填充
                    new System.Windows.Media.Pen(new SolidColorBrush(System.Windows.Media.Color.FromRgb(230, 126, 34)), 1.5), // 深橙色边框
                    geometry);
                
                var drawingGroup = new DrawingGroup();
                drawingGroup.Children.Add(drawing);
                
                var drawingImage = new DrawingImage(drawingGroup);
                drawingImage.Freeze();
                
                // 将DrawingImage转换为BitmapSource并缩放为图标大小
                var renderTarget = new RenderTargetBitmap(32, 32, 96, 96, PixelFormats.Pbgra32);
                var visual = new DrawingVisual();
                using (var context = visual.RenderOpen())
                {
                    context.DrawImage(drawingImage, new Rect(0, 0, 32, 32));
                }
                renderTarget.Render(visual);
                renderTarget.Freeze();
                
                Icon = renderTarget;
            }
            catch
            {
                // 如果设置图标失败，使用系统默认图标
                try
                {
                    if (icon != null)
                    {
                        Icon = Imaging.CreateBitmapSourceFromHIcon(
                            icon.Handle,
                            Int32Rect.Empty,
                            BitmapSizeOptions.FromEmptyOptions());
                    }
                }
                catch { }
            }
        }
    }
}

